import axios from "axios";
import store from "../store";
import JSONbig from "json-bigint";

const http = axios.create({
    baseURL: "/api",
    timeout: 10000,
    headers: {"Content-Type": "application/json;charset=UTF-8"},
    transformResponse: [
        function (data) {
            try {
                return JSONbig.parse(data);
            } catch (e) {
                return data;
            }
        }
    ]
});
http.interceptors.request.use(function (config) {
    if (config.headers) {
        config.headers["token"] = store().token;
    }
    return config;
}, function (error) {
    return Promise.reject(error);
});
http.interceptors.response.use(function (response) {
    const token = response.headers.token;
    if (token) {
        store().setToken(token);
    }
    const {data} = response;
    const code: number = data.code;
    const message: string = data.message;
    if (code === 0) {
        if (message) {
            window.$message.info(message);
        }
    } else if (code === -1) {
        window.$message.error(message);
    } else if (code === 1) {
        window.$message.warning(message);
    }
    return response;
}, function (error) {
    return Promise.reject(error);
});

interface CommonResult<T> {
    code: number,
    message: string,
    data: T
}

export const get = async <T = any>(url: string, params?: any): Promise<T> => {
    return new Promise<T>((resolve, reject) => {
        http.get<CommonResult<T>>(url, {params})
            .then(response => {
                resolve(response.data.data);
            })
            .catch(error => {
                reject(error.data);
            });
    });
}
export const post = <T = any>(url: string, params?: any): Promise<T> => {
    return new Promise<T>((resolve, reject) => {
        http.post<CommonResult<T>>(url, JSONbig.stringify(params))
            .then(response => {
                resolve(response.data.data);
            })
            .catch(error => {
                reject(error.data);
            });
    });
}
export const postForm = <T = any>(url: string, params?: any): Promise<T> => {
    return new Promise<T>((resolve, reject) => {
        http.postForm<CommonResult<T>>(url, params)
            .then(response => {
                resolve(response.data.data);
            })
            .catch(error => {
                reject(error.data);
            });
    });
}
